const express = require('express');
const cors = require('cors');
const app = express();
const PORT = 3000;

app.use(cors());
//跨域
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  res.setHeader('Access-Control-Allow-Credentials', true);
  next();
}
);

app.get('/req', (req, res) => {
  console.log(111);
  console.log(req.headers);
  res.send('Hello World!');
});

app.get('/events', (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  let count = 0;
  const sendEvent = () => {
    res.write(`data: ${JSON.stringify({ message: count++, time: Date.now() })}\n\n`);
  };

  // 每隔 2 秒发送一次消息
  const interval = setInterval(sendEvent, 200);

  setInterval(() => {
    clearInterval(interval);
    res.end();
  }, 10000);

  // 立即发送一条初始消息
  sendEvent();
});

app.listen(PORT, () => {
  console.log(`SSE server running at http://localhost:${PORT}`);
});
